// 初始化角色
function initRoleInfo() {
    $.ajax({
        url: 'queryRole',
        type: 'POST',
        data: {},
        async: true,
        dataType: 'JSON',
        success: function (resp) {
            console.log(resp);
            //获取角色数组
            arr = resp.datas.role;
            //1.将数据添加到搜索框中
            var searchRole = document.getElementById('searchRole');
            var modifyRole = document.getElementById('modifyRoleName');
            var addRole = document.getElementById('RoleName');
            //2.将数据添加到修改的下拉框中
            for (var i = 0; i < arr.length; i++) {
                searchRole.innerHTML += `<option value="${arr[i].roleId}">${arr[i].roleName}</option>`;
                modifyRole.innerHTML += `<option value="${arr[i].roleId}">${arr[i].roleName}</option>`;
                addRole.innerHTML += `<option value="${arr[i].roleId}">${arr[i].roleName}</option>`;
            }
            initAdmin();
        },
        error: function (err) {
            alert('请联系管理员！initRoleInfo');
        }
    })
}

initRoleInfo();

// 1.设置对应数量的搜索变量
var searchName = '';
var searchBDate = '';
var searchEDate = '';
var searchRole = -1;
// 2.设置分页变量
var start = 0; // 开始为止
var limit = 5; // 每页显示多少条
var end = 4; // 结束为止
var count = 0; // 一共多少条数据
var currPage = 1; // 当前第几页
var allPage = 0; // 一共多少页

function initAdmin() {
    $.ajax({
        url: 'admPage',
        type: 'POST',
        data: {
            'searchName': searchName,
            'searchBDate': searchBDate,
            'searchEDate': searchEDate,
            'searchRole': searchRole,
            'start': start,
            'limit': limit
        },
        dataType: 'JSON',
        async: true,
        success: function (resp) {
            console.log(resp);
            count = resp.datas.count;
            // 计算页码
            allPage = count % limit == 0 ? count / limit : parseInt(count / limit + 1);
            // 将页码显示到界面上
            var admPage = document.getElementById('admPage');
            admPage.innerHTML = currPage + "/" + allPage;

            var arr = resp.datas.admin;
            adminArr = arr;
            var dataBody = document.getElementById('dataBody');
            dataBody.innerHTML = '';
            for (var i = 0; i < arr.length; i++) {
                dataBody.innerHTML += `<tr>
					       <td class="data-td" >
						   <input class="selectItem" type="checkbox" />
					       </td >
					       <td class="data-td" >${arr[i].adminName}</td>
					       <td class="data-td" >${getRoleName(arr[i].roleId)}</td>
					       <td class="data-td" >${arr[i].adminState == 1 ? '启用': '禁用'}</td>
					       <td class="data-td" >${getDate(arr[i].adminCtime)}</td>
					       <td class="data-td">
						   <button class="btn" onclick="deleteAdm(${i})">删除</button>
						   <button class="btn" onclick="showModifyFrame(${i})">修改</button>
					</td>
				</tr>`
            }
        },
        error: function (err) {
            alert('请联系管理员initAdmin');
        }
    })
}

initAdmin();

// 解析时间，因为后端传过来的是数字，需要解析成对应的样式
function getDate(num) {
    if(!num) {
        return '解析错误';
    }
    var d = new Date(num);
    return d.getFullYear() + "-" +
        addZero(d.getMonth() + 1) + "-" +
        addZero(d.getDate()) + " " +
        addZero(d.getHours()) + ":" +
        addZero(d.getMinutes()) + ":" +
        addZero(d.getSeconds()) ;
}
// 补零
function addZero(data) {
    if(data > 9) {
        return data;
    }else {
        return "0" + data;
    }
}
// 获取角色信息
function getRoleName(id) {
    for(var i = 0; i < arr.length; i ++) {
        if(arr[i].roleId == id) {
            return arr[i].roleName;
        }
    }
}
//上一页
function doPre() {
    if(currPage == 1) {
        alert('已经是首页了!');
    }else {
        currPage --;
        start -= limit;
        end -= limit;
        initAdmin();
    }
}
//下一页
function doNext() {
    if(currPage == allPage) {
        alert('已经是尾页了!');
    }else {
        currPage ++;
        start += limit;
        end += limit;
        initAdmin();
    }
}
//搜索
function doSearch() {
    // 将所有的分页变量全部初始化
    start = 0; // 开始为止
    limit = 5; // 每页显示多少条
    end = 4; // 结束为止
    count = 0; // 一共多少条数据
    currPage = 1; // 当前第几页
    allPage = 0; // 一共多少页
    // 获取搜索框的值，赋值给搜索变量
    searchName = document.getElementById('sname').value;
    searchBDate = document.getElementById('sbdate').value;
    searchEDate = document.getElementById('sedate').value;
    searchRole = document.getElementById('searchRole').value;
    // 调用初始化方法
    initAdmin();
}

// function showTime() {
//     var t = new Date();//获取当前时间
//     var year = t.getFullYear(); //获取当前时间的年份
//     var month = t.getMonth(); //获取当前时间的月份
//     var day = t.getDate(); //获取当前时间的日
//     var hour = t.getHours(); //获取当前时间的时
//     var minute = t.getMinutes(); //获取当前时间的分
//     var second = t.getseconds(); //获取当前时间的秒
//     var showTime = year + "-" + month + "-" + day + " " + hour + ((minute < 10) ? ":0" : " :") + minute + ((second < 10) ? ":0" : ":") + second;//规范整体时间的输出
//     document.getElementById("admCTime").placeholder = showTime;
// }

//展示新增页面
function showAddFrame() {
    var frame = document.getElementById('addFrame');
    frame.style.display = "flex";
    // showTime();
}

//隐藏新增页面
function hideAddFrame() {
    var frame = document.getElementById('addFrame');
    frame.style.display = "none";
}

//保存数据并隐藏新增面板
function saveAddFrame() {
    $.ajax({
        url:'AddAdmin',
        type: 'POST',
        async: true,
        data: {
            name : document.getElementById('admName').value,
            rid: document.getElementById('RoleName').value,
        },
        dataType:'JSON',
        success: function (resp) {
            console.log(resp);
            alert(resp.message);
            if(resp.id > 0) {
                doSearch();
                hideAddFrame();
            }
        },
        error: function (err) {
            alert('请联系管理员saveAddFrame')
        }
    })
}

//删除
function deleteAdm(index) {
    console.log(index);
    var dt = confirm("确定删除?");
    if (dt == true) {
        $.ajax({
            url:'DeleteAdmin',
            type: 'POST',
            async: true,
            data: {
                id : adminArr[index].adminId
            },
            dataType:'JSON',
            success: function (resp) {
                console.log(resp);
                alert(resp.message);
                if(resp.id > 0) {
                    doSearch();
                }
            },
            error: function (err) {
                alert('请联系管理员deleteAdm')
            }
        })
    }
}

//展示修改面板
function showModifyFrame(index) {
    console.log(index);
    document.getElementById('modifyFrame').style.display = "flex";
    // 将数据添加到界面上
    document.getElementById('modifyAdmName').value = adminArr[index].adminName;
    document.getElementById('modifyRoleName').value = adminArr[index].roleId;
    document.getElementById('modifyAdmState').value = adminArr[index].adminState == 1 ? '启用': '禁用';
    adminIndex = index;
}

//隐藏修改面板
function hideModifyFrame() {
    var modifyFrame = document.getElementById('modifyFrame');
    modifyFrame.style.display = 'none';
}

// 保存修改面板
function saveModifyFrame() {
    var state;
    var state1 = document.getElementById('modifyAdmState').value;
    if (state1=='启用'){
        state=1;
    }else {
        state=2;
    }
    $.ajax({
        url:'editAdminById',
        type: 'POST',
        async: true,
        data: {
            name :  document.getElementById('modifyAdmName').value,
            rid: document.getElementById('modifyRoleName').value,
            state: state,
            id : adminArr[adminIndex].adminId
        },
        dataType:'JSON',
        success: function (resp) {
            console.log(resp);
            alert(resp.message);
            if(resp.id > 0) {
                doSearch();
                hideModifyFrame();
            }
        },
        error: function (err) {
            alert('请联系管理员saveModifyFrame')
        }
    })
}

//全选按钮的监听
function selectAll(obj) {
    var arr = document.getElementsByClassName('selectItem');
    for (var selectItem of arr) {
        selectItem.checked = obj.checked;
    }
}

//删除勾选的项
function removeSelect() {
    var arr = document.getElementsByClassName('selectItem');
    var arr1=[];
    var dt = confirm("确定删除?");
    if (dt == true) {
        //遍历选择的项
        for (var i = arr.length - 1; i >= 0; i--) {
            if (arr[i].checked == true) {
                // arr1.push(i);
                console.log(i);
                arr1.push(adminArr[i].adminId);

            }
            // }
        }

        $.ajax({
            url: 'DeleteAdmin1',
            type: 'POST',
            async: true,
            data: {
                id: arr1
            },
            dataType: 'JSON',
            success: function (resp) {
                console.log(resp);
                alert(resp.message);
                if (resp.id > 0) {
                    doSearch();
                }
            },
            error: function (err) {
                alert('请联系管理员removeSelect')
            }
        })
    }
}
